package com.sinoyd.itszyw.Activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.sinoyd.itszyw.Dialog.DownloadDialog;
import com.sinoyd.itszyw.Dialog.LoadingDialog;
import com.sinoyd.itszyw.Model.IssueInfo;
import com.sinoyd.itszyw.Model.MaintainTaskInfo;
import com.sinoyd.itszyw.Model.RegistrantInfo;
import com.sinoyd.itszyw.Model.RepairsDepInfo;
import com.sinoyd.itszyw.Model.RepairsInfo;
import com.sinoyd.itszyw.Model.RoutineInspectionInfo;
import com.sinoyd.itszyw.Model.TaskTypeInfo;
import com.sinoyd.itszyw.Model.VersionUpdate;
import com.sinoyd.itszyw.R;
import com.sinoyd.itszyw.Util.PreferencesUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.sinoyd.itszyw.MyApplication.GetAllUser;
import static com.sinoyd.itszyw.MyApplication.GetDepartment;
import static com.sinoyd.itszyw.MyApplication.GetInspection;
import static com.sinoyd.itszyw.MyApplication.GetLoginInfo;
import static com.sinoyd.itszyw.MyApplication.GetMaintainTasks;
import static com.sinoyd.itszyw.MyApplication.GetReleaseUser;
import static com.sinoyd.itszyw.MyApplication.GetTaskVariety;
import static com.sinoyd.itszyw.MyApplication.GetVersion;
import static com.sinoyd.itszyw.MyApplication.VERSION_DATA;
import static com.sinoyd.itszyw.MyApplication.db;
import static com.sinoyd.itszyw.MyApplication.logRrowGuid;
import static com.sinoyd.itszyw.MyApplication.loginId;
import static com.sinoyd.itszyw.MyApplication.loginName;
import static com.sinoyd.itszyw.MyApplication.versionCode;
import static com.sinoyd.itszyw.MyApplication.versionName;

/**
 * @createBy : Sinoyd 大饼洲
 * @description : 轻量级存储
 * @projectName : ITYW
 * @creationDate: 2017-03-09 15:28
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity {

    @ViewInject(R.id.user_account)
    EditText user_account;
    @ViewInject(R.id.user_password)
    EditText user_password;

    @ViewInject(R.id.box_account)
    CheckBox box_account;
    @ViewInject(R.id.box_password)
    CheckBox box_password;


    //登录
    private static int GET_LOGIN = 111;
    //维护任务
    private static int GET_MAINTAIN_TASK = 222;
    //任务类型
    private static int GET_TASK_TYPE = 333;
    //下发人
    private static int GET_ISSUER = 444;
    //报修人
    private static int GET_REPAIRS = 555;
    //报修部门
    private static int GET_REPAIRS_DEP = 666;

    //例行巡检
    private static int GET_INSPECTION = 777;


    private static int GET_VERSION = 000;
    private final int CODE_FOR_WRITE_PERMISSION = 1;

    private List<MaintainTaskInfo> list = new ArrayList();
    private List<TaskTypeInfo> listType = new ArrayList();
    private List<IssueInfo> listIssue = new ArrayList();
    private List<RepairsInfo> listRepairs = new ArrayList();
    private List<RepairsDepInfo> listRepairsDep = new ArrayList();
    private List<RegistrantInfo> listRegistrant = new ArrayList();
    private List<RoutineInspectionInfo> listInspection = new ArrayList();

    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        loadingDialog = new LoadingDialog(this, R.style.dialog_translucent_notitle);
        user_account.setText(PreferencesUtils.getStrng(this, "account"));
        user_password.setText(PreferencesUtils.getStrng(this, "password"));
        box_account.setChecked(PreferencesUtils.getBoolean(this, "accountBoolean"));
        box_password.setChecked(PreferencesUtils.getBoolean(this, "passwordBoolean"));

        VERSION_DATA = new VersionUpdate();
        getVersionDetail();

        RequestParams params = new RequestParams(GetVersion);
        params.addQueryStringParameter("validation", "sinoyd123!@#");

        try {
            sendHttpRequest(params, HttpMethod.GET, GET_VERSION);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void getVersionDetail() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            versionName = info.versionName;
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("version", "getError");
            e.printStackTrace();
        }
    }

    public void getVerion() {
        if (VERSION_DATA.VerCode != null) {
            if (Double.parseDouble(versionName) < Double.parseDouble(VERSION_DATA.VerCode)) {

                AlertDialog.Builder versiondialog = new AlertDialog.Builder(
                        this,
                        AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

                versiondialog.setTitle("版本更新");
                versiondialog.setMessage("当前版本" + versionName
                        + "\n" + "发现新版本" + VERSION_DATA.VerCode
//                            + "。\n更新内容：" + VERSION_DATA.VerValue
                        + "\n" + "是否更新新版本");
                versiondialog.setPositiveButton("立即更新",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(
                                    DialogInterface paramDialogInterface,
                                    int paramInt) {
                                DownloadDialog.Builder builder = new DownloadDialog.Builder(LoginActivity.this);
                                builder.create().show();
                            }
                        });
                versiondialog.setNegativeButton("暂不更新",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(
                                    DialogInterface paramDialogInterface,
                                    int paramInt) {
                                paramDialogInterface.dismiss();
                            }
                        });
                versiondialog.show();

            } else {
                showToast("当前为最新版本！");
            }
        } else {
        }
    }

    /**
     * SHA加密
     *
     * @param strSrc 明文
     * @return 加密之后的密文
     */
    public static String shaEncrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-1");// 将此换成SHA-1、SHA-512、SHA-384等参数
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }


    /**
     * byte数组转换为16进制字符串
     *
     * @param bts 数据源
     * @return 16进制字符串
     */
    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    @Override
    public void httpOnSuccess(String responseStr, int requestCode) {

        if (requestCode == GET_VERSION) {
            try {
                JSONObject objJSON = new JSONObject(responseStr);

                if (objJSON.getBoolean("IsSuccess")) {
                    JSONObject object = objJSON.getJSONArray("Data").getJSONObject(0);
                    VERSION_DATA = new VersionUpdate(object);

                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        //如果没有授权，则请求授权
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_FOR_WRITE_PERMISSION);
                    } else {
                        //有授权，直接询问是否下载
                        getVerion();

                    }

                } else {
                    showToast("获取版本失败~");
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        if (requestCode == GET_LOGIN) {
            try {

                loadingDialog.show();

                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {
                    JSONArray array = object.getJSONArray("Data");
                    JSONObject jsonObject = array.getJSONObject(0);
                    loginId = jsonObject.getString("user_id");
                    loginName = jsonObject.getString("user_name");
                    logRrowGuid = jsonObject.getString("RowGuid");
                    RequestParams params = new RequestParams(GetMaintainTasks);
                    params.addQueryStringParameter("RegistManID", "");
                    params.addQueryStringParameter("TaskType", "");
                    params.addQueryStringParameter("TaskStatus", "");
                    params.addQueryStringParameter("Size", "1000");
                    params.addQueryStringParameter("ProcessManID", loginId);
                    params.addQueryStringParameter("validation", "sinoyd123!@#");

                    try {
                        sendHttpRequest(params, HttpMethod.GET, GET_MAINTAIN_TASK);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    loadingDialog.dismiss();
                    showToast("账号密码不匹配!");
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        if (requestCode == GET_MAINTAIN_TASK) {
            try {
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {

                    JSONObject taskStaticObject = object.getJSONArray("Data").getJSONObject(0).getJSONArray("TaskStatic").getJSONObject(0);
                    JSONArray taskDataArray = object.getJSONArray("Data").getJSONObject(0).getJSONArray("TaskData").getJSONObject(0).getJSONArray("PageData");

                    int flag = 0;
                    Set set = new HashSet<String>();
                    for (int i = taskDataArray.length() - 1; i >= 0 ; i--) {
                        RegistrantInfo registrantInfo = new RegistrantInfo();
                        MaintainTaskInfo taskInfo = new MaintainTaskInfo();
                        try {
                            taskInfo.ParseMaintainTaskInfo(taskDataArray.getJSONObject(i));
                            registrantInfo.ParseRegistrantInfo(taskDataArray.getJSONObject(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        list.add(taskInfo);
                        if (!(registrantInfo.registrantName.equals(""))){
                            set.add(registrantInfo.registrantName);
                            if (set.size() > flag) {
                                listRegistrant.add(registrantInfo);
                                flag = set.size();
                            }
                        }



                    }

                    if (list.size() == 0){
                        RegistrantInfo registrantInfo = new RegistrantInfo();
                        MaintainTaskInfo taskInfo = new MaintainTaskInfo();
                        list.add(taskInfo);
                        listRegistrant.add(registrantInfo);
                        try {
                            db.save(list);
                            db.save(listRegistrant);
                            db.delete(MaintainTaskInfo.class);
                            db.delete(RegistrantInfo.class);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                    }else {
                        try {

                            db.dropTable(MaintainTaskInfo.class);
                            db.dropTable(RegistrantInfo.class);
                            db.save(list);
                            db.save(listRegistrant);

                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                    }



                    RequestParams params = new RequestParams(GetTaskVariety);
                    params.addQueryStringParameter("validation", "sinoyd123!@#");
                    try {
                        sendHttpRequest(params, HttpMethod.GET, GET_TASK_TYPE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    showToast("获取任务数据失败");
                    loadingDialog.dismiss();
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        if (requestCode == GET_TASK_TYPE) {
            try {
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {

                    JSONArray typeDataArray = object.getJSONArray("Data");


                    for (int i = 0; i < typeDataArray.length(); i++) {
                        TaskTypeInfo taskTypeInfo = new TaskTypeInfo();
                        try {
                            taskTypeInfo.ParseTaskTypeInfo(typeDataArray.getJSONObject(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        listType.add(taskTypeInfo);
                    }

                    try {
                        db.dropTable(TaskTypeInfo.class);
                        db.save(listType);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                    RequestParams params = new RequestParams(GetReleaseUser);
                    params.addBodyParameter("validation", "sinoyd123!@#");
                    try {
                        sendHttpRequest(params, HttpMethod.POST, GET_ISSUER);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    showToast("获取任务类型失败");
                    loadingDialog.dismiss();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (requestCode == GET_ISSUER) {
            try {
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {

                    JSONArray issuerDataArray = object.getJSONArray("Data");


                    for (int i = 0; i < issuerDataArray.length(); i++) {
                        IssueInfo issueInfo = new IssueInfo();
                        try {
                            issueInfo.ParseIssuerInfo(issuerDataArray.getJSONObject(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        listIssue.add(issueInfo);
                    }

                    try {
                        db.dropTable(IssueInfo.class);
                        db.save(listIssue);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                    RequestParams params = new RequestParams(GetAllUser);
                    params.addBodyParameter("validation", "sinoyd123!@#");
                    try {
                        sendHttpRequest(params, HttpMethod.POST, GET_REPAIRS);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    showToast("获取下发人失败");
                    loadingDialog.dismiss();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (requestCode == GET_REPAIRS) {
            try {
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {

                    JSONArray repairsDataArray = object.getJSONArray("Data");
                    for (int i = 0; i < repairsDataArray.length(); i++) {
                        RepairsInfo repairsInfo = new RepairsInfo();
                        try {
                            repairsInfo.ParseRepairsInfo(repairsDataArray.getJSONObject(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        listRepairs.add(repairsInfo);
                    }

                    try {
                        db.dropTable(RepairsInfo.class);
                        db.save(listRepairs);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                    RequestParams params = new RequestParams(GetDepartment);
                    params.addBodyParameter("validation", "sinoyd123!@#");
                    try {
                        sendHttpRequest(params, HttpMethod.POST, GET_REPAIRS_DEP);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    showToast("获取报修人失败");
                    loadingDialog.dismiss();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (requestCode == GET_REPAIRS_DEP) {
            try {
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {

                    JSONArray repairsDepDataArray = object.getJSONArray("Data");

                    for (int i = 0; i < repairsDepDataArray.length(); i++) {
                        RepairsDepInfo repairsDepInfo = new RepairsDepInfo();
                        try {
                            repairsDepInfo.ParseRepairsDepInfo(repairsDepDataArray.getJSONObject(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        listRepairsDep.add(repairsDepInfo);
                    }

                    try {
                        db.dropTable(RepairsDepInfo.class);
                        db.save(listRepairsDep);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                    RequestParams params = new RequestParams(GetInspection);
                    params.addBodyParameter("validation", "sinoyd123!@#");
                    try {
                        sendHttpRequest(params, HttpMethod.POST, GET_INSPECTION);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    showToast("获取报修部门失败");
                    loadingDialog.dismiss();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (requestCode == GET_INSPECTION) {

            try {
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {
                    JSONArray array = object.getJSONArray("Data");
                    for (int i = 0; i < array.length(); i++) {
                        RoutineInspectionInfo inspectionInfo = new RoutineInspectionInfo();
                        try {
                            inspectionInfo.ParseRoutineInspectionInfo(array.getJSONObject(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        listInspection.add(inspectionInfo);

                    }
                    try {
                        db.dropTable(RoutineInspectionInfo.class);
                        db.save(listInspection);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }


                    setSharePreferences();


                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    finish();

                } else {

                    showToast("获取巡检项数据失败!");
                    loadingDialog.dismiss();
                }
                loadingDialog.dismiss();
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }


    }


    private void setSharePreferences() {

        PreferencesUtils.putString(this, "account", "");
        PreferencesUtils.putString(this, "password", "");
        PreferencesUtils.putBoolean(this, "accountBoolean", false);
        PreferencesUtils.putBoolean(this, "passwordBoolean", false);


        if (box_password.isChecked()) {

            PreferencesUtils.putString(this, "account", user_account.getText().toString());
            PreferencesUtils.putString(this, "password", user_password.getText().toString());
            PreferencesUtils.putBoolean(this, "passwordBoolean", true);

        } else if (box_account.isChecked()) {

            PreferencesUtils.putString(this, "account", user_account.getText().toString());
            PreferencesUtils.putString(this, "password", "");
            PreferencesUtils.putBoolean(this, "accountBoolean", true);
        }
    }


    @Event({R.id.btn_login, R.id.box_account, R.id.box_password})
    private void getOnclik(View view) {
        switch (view.getId()) {
            case R.id.btn_login:

                if (user_account.getText().toString().equals("") || user_password.getText().toString().equals("")) {
                    showToast("请输入账号密码");
                } else {
                    String password = shaEncrypt(user_password.getText().toString());
                    RequestParams params = new RequestParams(GetLoginInfo);
                    params.addQueryStringParameter("loginId", user_account.getText().toString());
                    params.addQueryStringParameter("pwd", password);
                    params.addQueryStringParameter("validation", "sinoyd123!@#");

                    try {
                        sendHttpRequest(params, HttpMethod.GET, GET_LOGIN);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                break;
            case R.id.box_account:

                box_password.setChecked(false);

                break;
            case R.id.box_password:

                box_account.setChecked(false);

                break;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CODE_FOR_WRITE_PERMISSION){
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    &&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //用户同意使用write
                getVerion();
            }else{
                //用户不同意，自行处理即可
                //授权失败
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

}


